#ifndef QSERIALPROTO_H
#define QSERIALPROTO_H

#include <QObject>
#include <QDebug>
#include "inc/fsm.h"
#include <thread>

using namespace std;

typedef enum{
    INDATA = 0,
    Connect,
    Read,
    Write,
    DisConnect,
    ANALYSEFINISH,
    ANALYSEINPROGRESS
}AnalyseAction;

typedef struct{
    uint8_t funcode;
    uint8_t len;
    char *data;
}ProtoData;

typedef enum{
    StateUnConnected,
    StateNOPACKAGE,
    StateINPACKAGE,
}AnalyseState;

class SerialListener;
class SerialListener{
    virtual void OnPackage(ProtoData){};
};

/*
 |  8bit   |  8bit |  data    |  verify  |
    fun       len      ....      verify
fun: package type
len: package length
verify: verify data
*/
class QSerialProto : public QObject,
        StateMachine<AnalyseAction,AnalyseState> {
    Q_OBJECT
public:
    typedef enum {
        TYPE_DATA = 0,
    }PackageType;

    explicit QSerialProto(QObject *parent = nullptr);
    virtual void OnSerailData(QByteArray data);
    int UpdateState(AnalyseAction);
    void SetListener(class SerialListener * listener){
        this->mListener = listener;
    };
    int WriteData(uint8_t fun,uint8_t *data,uint8_t len);

signals:
    void OnPackage(ProtoData);
private:
    char mUnsortData[256];
    uint8_t mUnsortLen;
    uint8_t mRecvDataLen;
    SerialListener *mListener;
    std::thread mThread;
};

#endif // QSERIALPROTO_H
